#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <openssl/modes.h>
#include <openssl/aes.h>
#include <QTextCodec>
#include "Padding.h"


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

bool ecb_encrypt(const QByteArray &in, QByteArray &out, const QByteArray &key, bool enc)
{
    // 检查密钥合法性(只能是16字节)
    qDebug()<<key.size()<<endl;
    Q_ASSERT(key.size() == 16);

    if (enc)
    {
        // 生成加密key
        AES_KEY aes_key;
        if (AES_set_encrypt_key((const unsigned char*)key.data(), key.size() * 8, &aes_key) != 0)
        {
            return false;
        }

        // 进行PKCS7Padding填充
        QByteArray inTemp = Padding::PKCS7Padding(in, AES_BLOCK_SIZE);

        qDebug()<<AES_BLOCK_SIZE<<endl;

        // 执行ECB模式加密
        out.resize(inTemp.size()); // 调整输出buf大小
        for (int i = 0; i < inTemp.size() / AES_BLOCK_SIZE; i++)
        {
            AES_ecb_encrypt((const unsigned char*)inTemp.data() + AES_BLOCK_SIZE * i,
                            (unsigned char*)out.data() + AES_BLOCK_SIZE * i,
                            &aes_key,
                            AES_ENCRYPT);
        }
        return true;
    }
    else
    {
        // 生成解密key
        AES_KEY aes_key;
        if (AES_set_decrypt_key((const unsigned char*)key.data(), key.size() * 8, &aes_key) != 0)
        {
            return false;
        }

        // 执行ECB模式解密
        out.resize(in.size()); // 调整输出buf大小
        for (int i = 0; i < in.size() / AES_BLOCK_SIZE; i++)
        {
            AES_ecb_encrypt((const unsigned char*)in.data() + AES_BLOCK_SIZE * i,
                            (unsigned char*)out.data() + AES_BLOCK_SIZE * i,
                            &aes_key,
                            AES_DECRYPT);
        }

        // 解除PKCS7Padding填充
        out = Padding::PKCS7UnPadding(out);
        return true;
    }
}


void MainWindow::on_pushButton_clicked()
{
    QString input = ui->lineEdit->text();
    QByteArray data = input.toUtf8(); //转换类型
    qDebug()<<"data:"<<data;
    //加密
    QByteArray miwen;
    QByteArray mingwen;
    QByteArray key = QByteArray::fromHex("8cc72b05705d5c46f412af8cbed55aad");

    ecb_encrypt(data, miwen, key, true);//对data进行加密得到密文miwen
    qDebug()<<"密文："<<miwen;

    QString output = miwen.toBase64(); //转换成base64编码格式
    qDebug()<<"base64:"<<output;

    ui->lineEdit_2->setText(output);  //输出到控件
}

void MainWindow::on_pushButton_2_clicked()
{
    QString input = ui->lineEdit_2->text(); //获取base64编码格式的输入
    QByteArray data = QByteArray::fromBase64(QString(input).toLatin1()); //转换类型

    //解密
    QByteArray mingwen;
    QByteArray key = QByteArray::fromHex("8cc72b05705d5c46f412af8cbed55aad");

    ecb_encrypt(data, mingwen, key, false); //解码
    QString output;
    output.prepend(mingwen);  //转换成string类型准备输出

    ui->lineEdit->setText(output); //输出到控件
}
